package com.ehotting.edsta.mqbd.signal.netty.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.ehotting.eaf.core.constant.NettyActionConstant;
import com.ehotting.eaf.netty.client.ConnectorIdleStateTrigger;
import com.ehotting.eaf.netty.constant.NettyConstant;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;

import java.util.concurrent.TimeUnit;

@Sharable
public class SiIdleStateTrigger extends ConnectorIdleStateTrigger {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 处理接收到的数据...
        JSONObject requestJson = JSON.parseObject(evt.toString(), JSONObject.class, Feature.OrderedField);

        /**处理业务**/
        String action = (String)requestJson.get(NettyConstant.ACTION);
        if (NettyActionConstant.HEART_BEAT.equals(action)||NettyActionConstant.REGISTER.equals(action)){
            // 如果是注册/心跳信息就跳过
            ctx.fireChannelRead(evt);
            return;
        }
        // 在接收到数据后，延迟发送心跳消息
        ctx.executor().schedule(() -> {
            // 发送心跳消息的逻辑
            logger.info("Sending heartbeat...");
        }, 5, TimeUnit.SECONDS);

        if(msg!=null) {
            ctx.writeAndFlush(msg);
        }
        ctx.fireChannelRead(evt);
    }
}
